// pages/detail-search/index.js
import {playerStore} from '../../store/index'
const db = wx.cloud.database()
Page({
  data: {
    hotKeywords:[],
    searchValue:"",
    resultSongs:[],
    resultSongsIndex:0
  },

  onLoad: function (options) {
    this.getPageData()
  },

  //网络请求
  getPageData:function(){
    //将歌曲进行排序
    var that = this
     db.collection('songs')
    .orderBy('playCount','desc')
    .limit(10)
    .get()
    .then(res =>{
      that.setData({hotKeywords:res.data})
    })
    
    // getSearchHot().then(res =>{
    //   this.setData({ hotKeywords:res.result.hots })
    // })
  },

  //事件处理
  handleSearchChange:async function(event){
    //获取关键字
    const searchValue = event.detail
    this.setData({searchValue})
    //判断关键字为空字符串的处理逻辑
    if(!searchValue.length){
      this.setData({ resultSongs:[] })
      return
    } 

    //根据关键字进行搜索
    var that = this
    await db.collection('songs').where({
      name:db.RegExp({
        regexp:searchValue,
        options:"i"
      })
    })
    .get().then(res=>{
      that.setData({ resultSongs :res.data })
      that.setData({
        resultSongsIndex:that.data.resultSongs.length *1
      })
    })

    await db.collection('songs').where({
      'ar.name':db.RegExp({
        regexp:searchValue,
        options:"i"
      })       
    })
    .get().then(res=>{
      
      if(res.data.length){
         var index = this.data.resultSongsIndex
        for(var i=0 ; i < res.data.length;i++){
          var answerK = "resultSongs["+index+"]"

          this.setData({
          [answerK] :res.data[i]
          })
          index++
        }
        
      }
      
    })
    
    
    console.log(this.data.resultSongs);

  },
  handleTapAction:function(){
    const searchValue = this.data.searchValue
     //根据关键字进行搜索
     var that = this
     const _ = db.command
     db.collection('songs').where({
       name:db.RegExp({
         regexp:searchValue,
         options:"i"
       }),
      
     })
     .get().then(res=>{
       that.setData({ resultSongs :res.data })
     })

    
  },
  handleKeywordItemClick:function(event){
    //获取点击的关键字
    const keyword = event.currentTarget.dataset.keyword

    //将关键字设置到searchvalue中
    this.setData({searchValue:keyword})

    //发送网络请求
    this.handleTapAction()
  },

  //=========================点击歌曲===========================
  handleSongItemClick:function(event){
    const index = event.currentTarget.dataset.index
    playerStore.setState("playListSongs",this.data.resultSongs)
    playerStore.setState("playListIndex", index)
  },
  
})